package com.java2001.controller;


import com.java2001.pojo.Book;
import com.java2001.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookServiceImpl;

    /**
     * 跳转到图书管理页面
     *
     * @return 所有图书
     */
    @RequestMapping("/books")
    public String toBooks(Model model) {
        model.addAttribute("bookList", bookServiceImpl.queryBookList());
        return "book/books";
    }

    /**
     * 跳转到添加图书页面
     *
     * @return
     */
    @RequestMapping("/toAddBook")
    public String toAddBook() {
        return "book/addBook";
    }

    /**
     * 添加图书 提交表单
     *
     * @param book
     * @param model
     * @return
     */
    @RequestMapping("/addBook")
    public String addBook(Book book, Model model) {
        if (bookServiceImpl.queryBookById(book.getIsbn()) == null) {
            bookServiceImpl.insertBook(book);
            return "redirect:/book/books";
        } else {
            model.addAttribute("msg", "已存在此isbn");
            return "forward:/book/toAddBook";
        }
    }

    /**
     * 跳转到更新图书的页面
     *
     * @return
     */
    @RequestMapping("/toUpdateBook/{isbn}")
    public String toUpdateBook(@PathVariable("isbn") String isbn, Model model) {

        Book book = bookServiceImpl.queryBookById(isbn);

        model.addAttribute("book", book);

        return "book/updateBook";
    }


    /**
     * 删除书本 提交表单
     *
     * @param book
     * @return
     */
    @RequestMapping("/updateBook")
    public String updateBook(Book book) {

        bookServiceImpl.updateBookById(book);
        return "redirect:/book/books";
    }

    /**
     * 根据isbn删除图书
     *
     * @param isbn
     * @return
     */
    @RequestMapping("/deleteBook/{isbn}")
    public String deleteBook(@PathVariable("isbn") String isbn) {
        bookServiceImpl.deleteBookById(isbn);
        return "redirect:/book/books";
    }

    /**
     * 根据isbn和书名，模糊查询图书
     * @param book
     * @param model
     * @return
     */
    @RequestMapping("/searchBook")
    public String searchBook(Book book,Model model){
        book.setIsbn(book.getIsbn() == "" ? null : book.getIsbn());
        book.setBookName(book.getBookName() == "" ? null : book.getBookName());
        List<Book> bookList = bookServiceImpl.queryBookByIsbnOrBookName(book);
        System.out.println("Controller ==> " + bookList);
        model.addAttribute("bookList",bookList);
        return "book/books";
    }

}
